package com.dwh.web.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *
 * @author 李文庆
 * 2019年3月20日 下午4:59:41
 */
@Configuration
@EnableCaching
@EnableAsync
public class WebMvcConfiguration implements WebMvcConfigurer {

	private final String[] ORIGINS = new String[] { "GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"};

	
	/**
	 * 使用fastjson处理返回json
	 */
	@Bean  
	public HttpMessageConverters fastJsonHttpMessageConverters() {

	    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();  
	    FastJsonConfig fastJsonConfig = new FastJsonConfig();  
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,  //允许值为null的键存在
												SerializerFeature.BrowserCompatible);
	    fastConverter.setFastJsonConfig(fastJsonConfig);

		return new HttpMessageConverters(fastConverter);
	}

	/**
	 * 解决跨域问题
	 */
	@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods(ORIGINS);
    }

}
